package com.squid.templateProject.utils;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Description 用于去除对象中String字符串两端的空格和特殊符号，单独String对象不可使用
 *
 * @author jinhang1
 * @since 2024/01/04
 */
@Slf4j
public class TrimStringUtils {
    private static final String CLASS_TYPE_STRING = "java.lang.String";
    private static final Pattern pattern = Pattern.compile("^[^\\u4e00-\\u9fa5a-zA-Z0-9]+|[^\\u4e00-\\u9fa5a-zA-Z0-9]+$");

    public static <T> void trim(T obj) {
        Class<?> aClass = obj.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        Arrays.stream(declaredFields).forEach(x -> {
            x.setAccessible(true);
            if (x.getGenericType().getTypeName().equals(CLASS_TYPE_STRING)) {
                try {
                    String fieldProperties = (String) x.get(obj);
                    if (StringUtils.hasText(fieldProperties)) {
                        String result = replace(fieldProperties);
                        x.set(obj, result);
                    }
                } catch (IllegalAccessException e) {
                    log.error("删除字符串两端空格和特殊字符失败", e);
                    throw new RuntimeException(e);
                }
            }
        });
//        return obj;
    }

    private static String replace(String fieldProperties) {
        // 使用正则表达式去除两边空格和特殊字符
        Matcher matcher = pattern.matcher(fieldProperties);
        return matcher.replaceAll("").trim();
    }

    public static void main(String[] args) {
        String str = "   ***Hello!@#$%^&*() World你好?***** ";
        A build = A.builder().test(str).build();
        TrimStringUtils.trim(build);
//        System.out.println(trim);
        System.out.println(build);

    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Builder
    static class A {
        private String test;
    }
}
